﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace AllenHung.FeedReader
{
    public partial class AddCustomFeedPage : PhoneApplicationPage
    {
        public AddCustomFeedPage()
        {
            InitializeComponent();
        }

        private void OK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(NewFeedName.Text) || string.IsNullOrWhiteSpace(NewFeedName.Text))
            {
                ErrorText.Visibility = Visibility.Visible;
                ErrorText.Text = "Feed name can't be empty";
            }
            else if (string.IsNullOrEmpty(NewFeedURL.Text) || string.IsNullOrWhiteSpace(NewFeedURL.Text))
            {
                ErrorText.Visibility = Visibility.Visible;
                ErrorText.Text = "Feed URL can't be empty";
            }
            else if (!NewFeedURL.Text.StartsWith("http://") && !NewFeedURL.Text.StartsWith("https://"))
            {
                ErrorText.Visibility = Visibility.Visible;
                ErrorText.Text = "Invalid URL";
            }
            else
            {
                ErrorText.Visibility = Visibility.Collapsed;
                FeedSource fs = new FeedSource
                {
                    SourceName = NewFeedName.Text,
                    IsSubscribed = true,
                    SourceImagePath = "/Assets/feedicon.png",
                    SourceUri = NewFeedURL.Text
                };
                MainPage.MainModel.FeedSources.InsertOnSubmit(fs);
                MainPage.MainModel.SubmitChanges();
                MainPage.SubscribedFeedSources.Add(fs);
                MainPage.AllFeedSources.Add(fs);
                BackToMainPage();
            }
        }

        private void Cancel_Click(object sender, EventArgs e)
        {
            BackToMainPage();
        }

        private void BackToMainPage()
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ErrorText.Visibility = Visibility.Collapsed;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
        }
    }
}